package com.yunshu.yunshuapp.tongxunlu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.OnTapListener;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.kuaixun.KuaixunChannel;
import com.yunshu.yunshuapp.kuaixun.TypeListAdapter;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.YSUser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhouwenjie on 2017/2/1.
 */
public abstract class ButtonsListActivity extends AppCompatActivity implements View.OnClickListener, OnTapListener {

    private static final int MSG_TYPES_UPDATE = 1111;
    private static final int MSG_CITIES_UPDATE = 2222;
    protected RecyclerView mRecyclerView;
    protected RecyclerView mTypeList;
    protected SwipeRefreshLayout mTypeRefreshLayout;
    protected TypeListAdapter mTypeAdapter;
    protected RecyclerView mCityList;
    protected TypeListAdapter mCityAdapter;

    protected int typePageIndex = 0;
    protected int pageIndex = 0;
    protected YSRequest typeRequest;
    protected List models;
    protected RecyclerView.Adapter adapter;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected NavigationBar navigationBar;

    private Handler mExtHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottons);
        navigationBar = (NavigationBar)findViewById(R.id.navigationBar);
        navigationBar.putInActivity(this);

        typeRequest = new YSRequest(this);

        this.initRecyleView();
        this.initTypeList();
        this.initCityList();

        this.initListener();

        this.refreshTypes();

        this.refresh();

        mExtHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_TYPES_UPDATE:
                        mTypeAdapter.notifyDataSetChanged();
                        break;
                    case MSG_CITIES_UPDATE:
                        mCityAdapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };
    }

    private void initTypeList() {
        mTypeList = (RecyclerView) findViewById(R.id.typeLIST);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mTypeList.setLayoutManager(mLayoutManager);
        mTypeList.setHasFixedSize(true);
        mTypeAdapter = new TypeListAdapter(getBaseContext());
        mTypeAdapter.activity = this;
        mTypeAdapter.tapListener = this;
        mTypeList.setAdapter(mTypeAdapter);

//        mTypeList.setAdapter(mTypeAdapter);

        mTypeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.slection_swipe_container1);
        //设置刷新时动画的颜色，可以设置4个
        mTypeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        mTypeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refreshTypes();
            }
        });

    }

    private void initCityList() {
        String[] cities = new String[]{"全部","北京市","天津市","河北省","山西省","内蒙古自治区","辽宁省","吉林省","黑龙江省","上海市","江苏省","浙江省","安徽省","福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","广西壮族自治区","海南省","四川省","贵州省","云南省","重庆市","西藏自治区","陕西省","甘肃省","青海省","宁夏回族自治区","新疆维吾尔自治区","香港特别行政区","澳门特别行政区","台湾省"};
        ArrayList<KuaixunChannel> cityList = new ArrayList<KuaixunChannel>();
        for (String city : cities){
            KuaixunChannel newCity = new KuaixunChannel();
            newCity.setTitle(city);
            newCity.setChannelId(city);
            cityList.add(newCity);
        }
        mCityList = (RecyclerView) findViewById(R.id.cityLIST);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mCityList.setLayoutManager(mLayoutManager);
        mCityList.setHasFixedSize(true);
        mCityAdapter = new TypeListAdapter(getBaseContext());
        mCityAdapter.activity = this;
        mCityAdapter.setModels(cityList);
        mCityAdapter.tapListener =this;
        mCityList.setAdapter(mCityAdapter);

    }

    protected void initRecyleView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.list_view);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        //设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refresh();
            }
        });

    }

    private void initListener() {

        Button typeBTN = (Button) findViewById(R.id.typeBTN);
        typeBTN.setOnClickListener(this);

        Button cityBTN = (Button) findViewById(R.id.cityBTN);
        cityBTN.setOnClickListener(this);

        this.addLoadMoreListener(this.mRecyclerView);
        this.addLoadMoreListener(this.mTypeList);
    }

    private void addLoadMoreListener(final RecyclerView list) {
        list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==mRecyclerView.getAdapter().getItemCount()){
                    loadmore(list);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void loadmore(RecyclerView list) {
        if (list == mRecyclerView){
            this.loadmore();
        }else if(list == mTypeList){
            this.loadmoreTypes();
        }
    }

    protected abstract void refresh() ;

    protected abstract void loadmore() ;

    private void refreshTypes() {
        if (!typeRequest.getIsCompleted()){
            return;
        }
        typePageIndex = 1;
        typeRequest.GET(YSRequest.Kuaixun_Channels, "&page=1", new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshingTypes();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<KuaixunChannel> temp = new ArrayList<KuaixunChannel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        KuaixunChannel model = mapper.readValue(jsonstr, KuaixunChannel.class);
                        model.isSelected = false;
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mTypeAdapter.setModels(temp);
                typePageIndex +=1;
                reloadTypes();
            }
        });
    }

    private void loadmoreTypes() {
        if (!typeRequest.getIsCompleted()) return;
        typeRequest.GET(YSRequest.Kuaixun_Channels,"&page="+typePageIndex, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshingTypes();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<KuaixunChannel> temp = new ArrayList<KuaixunChannel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        KuaixunChannel model = mapper.readValue(jsonstr, KuaixunChannel.class);
                        model.isSelected = false;
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                typePageIndex +=1;
                mTypeAdapter.addFooterItem(temp);

                reloadTypes();
            }
        });
    }

    private void reloadTypes() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                mTypeAdapter.notifyDataSetChanged();
            }
        });

//        Message msg;
//        msg = Message.obtain();
//        msg.what = MSG_TYPES_UPDATE;
//        mExtHandler.sendMessage(msg);
    }
    private void endRefreshingTypes() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                mTypeRefreshLayout.setRefreshing(false);
            }
        });

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.typeBTN){
            mTypeRefreshLayout.setVisibility(View.VISIBLE);
            mCityList.setVisibility(View.INVISIBLE);
            mTypeAdapter.notifyDataSetChanged();
        }else if(view.getId() == R.id.cityBTN){
            mCityList.setVisibility(View.VISIBLE);
            mTypeRefreshLayout.setVisibility(View.INVISIBLE);
            mCityAdapter.notifyDataSetChanged();

        }
    }

    protected abstract void onFilterChange(String types, String cities) ;

    @Override
    public void onSingleTap(View v, int position) {
        StringBuffer types = new StringBuffer();
        for (KuaixunChannel channel : mTypeAdapter.getModels()){
            if (!channel.isSelected) continue;
            if (types.length() >0 ) types.append(",");
            types.append(channel.getTitle());
        }
        StringBuffer cities = new StringBuffer();
        for (KuaixunChannel channel : mCityAdapter.getModels()){
            if (!channel.isSelected) continue;
            if (cities.length() >0 ) cities.append(",");
            cities.append(channel.getTitle());
        }
        this.onFilterChange(types.toString(),cities.toString());

        mTypeRefreshLayout.setVisibility(View.GONE);
        mCityList.setVisibility(View.GONE);
    }
}
